﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoNyaa.Logic.Entities;
using System.Threading;
using System.Net;

namespace AutoNyaa.Logic
{
    public class DownloadManager
    {
        public List<Download> Downloads { get; set; }

        private bool _exit;

        private static DownloadManager _downloadManager;
        private static Thread _downloadThread;
        private static TorrentManagerWrapper _torrentManagerWrapper;


        public static void StartDownload(string url, string location)
        {
            if (_downloadManager == null)
            {
                _torrentManagerWrapper = new TorrentManagerWrapper(@"C:\Users\d.hellewegen\Documenten\bt\");
                _downloadManager = new DownloadManager();
                _downloadThread = new Thread(new ThreadStart(_downloadManager.Run));
                _downloadThread.IsBackground = true;
                _downloadThread.Start();
            }

            Download download = new Download()
            {
                Url = url,
                Location = location,
                Downloaded = false
            };
            _downloadManager.Downloads.Add(download);
        }

        public DownloadManager()
        {
            Downloads = new List<Download>();
            _exit = false;
        }


        public void Run()
        {
            while (!_exit)
            {
                Download[] downloads = Downloads.ToArray();

                foreach (Download download in downloads)
                {
                    if (!download.Downloaded)
                    {
                        Console.WriteLine("Downloading " + download.Url);
                        download.Location += ".torrent";

                        WebClient webClient = new WebClient();
                        webClient.DownloadFile(new Uri(download.Url), download.Location);
                        download.Downloaded = true;

                        _torrentManagerWrapper.StartTorrent(download.Location);
                    }
                }

                Thread.Sleep(1000);
            }
        }

        public void Exit()
        {
            _exit = true;
        }

        public static void ExitAll()
        {
            if (_downloadManager != null)
            {
                _downloadManager.Exit();
            }

            _torrentManagerWrapper.Exit();

            if (_downloadThread != null && _downloadThread.IsAlive)
            {
                _downloadThread.Join();
            }
            
        }
    }
}